<template>
    <div class="app-container">
        <el-form
            :inline="true"
            size="mini"
            class="searchForm"
            ref="searchForm"
            :model="searchForm"
        >
            <el-form-item label="设备类型">
                <el-select
                    clearable
                    v-model="searchForm.equipTypeCode"
                    placeholder="请选择设备类型"
                    @change="equipTypeChange"
                >
                    <el-option
                        v-for="item in equipTypeList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="部件">
                <el-select
                    clearable
                    v-model="searchForm.partTypes"
                    :disabled="!searchForm.equipTypeCode"
                    multiple
                    placeholder="请选择部件"
                >
                    <el-option
                        v-for="item in componentList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="版本">
                <el-input
                    clearable
                    v-model="searchForm.version"
                    placeholder="请选择版本"
                ></el-input>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doSearch"
                    >搜索</el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetSearch"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <div class="searchs-content">
            <el-button
                v-permission="['version:manager:add']"
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                @click="addDialog"
                >新增</el-button
            >
        </div>
        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="isUpdate" slot-scope="scope">
                <el-switch
                    v-permission="['version:manager:cancelauto']"
                    v-model="scope.row.isAutoUpgrade"
                    :active-value="1"
                    :inactive-value="0"
                    @change="isCancelUpdate($event, scope.row)"
                >
                </el-switch>
            </template>
            <template slot="connection" slot-scope="scope">
                <el-button
                    plain v-permission="['version:manager:devices']"
                    size="mini"
                    type="primary"
                    @click="showEquipList(scope.row)"
                    >设备列表</el-button
                >
            </template>
            <template slot="action" slot-scope="scope">
                <el-button
                    v-permission="['version:manager:edit']"
                    type="primary"
                    size="mini"
                    @click="addDialog(scope.row)"
                    >编辑</el-button
                >
                <el-button
                    v-permission="['version:manager:delete']"
                    type="danger"
                    size="mini"
                    @click="delDialog(scope.row)"
                    >删除</el-button
                >
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 弹框 -->
        <Dialog
            :visible="visible"
            width="45%"
            :title="dialogTitle"
            :isFooter="false"
            @cancelDialog="cancelDialog"
            class="detailDialog"
        >
            <WareVersion
                :updateDialogVisible="visible"
                :currentRow="dialogForm"
                :equipTypeList="equipTypeList"
                @cancelDialog="cancelDialog"
                @updateData="updateData"
            ></WareVersion>
        </Dialog>

        <!-- 连接设备 -->
        <Dialog
            :visible="equipVisible"
            width="80%"
            :isFullscreen="isFullscreen"
            title="关联设备"
            @cancelDialog="cancelEquipDialog" :isFooter="false"
        ><i
            class="el-icon-full-screen"
            @click="onFullscreen('isFullscreen')"
        ></i>
            <connect-equip :isFullscreen="isFullscreen" :equipVisible="equipVisible" :versionId="versionId"></connect-equip>
        </Dialog>
    </div>
</template>

<script>
import { softwareVersion, partType, softwareVersions } from "@/api/file";
import { equipType, equipment } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import WareVersion from "./wareVersion";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";
import { mapState, mapGetters } from "vuex";

import moment from "moment";
import ConnectEquip from "./connectEquip.vue";
export default {
    components: { Pagination, Table, Dialog, WareVersion, ConnectEquip },
    filters: {
        statusFilter(status) {
            const statusMap = {
                published: "success",
                draft: "gray",
                deleted: "danger",
            };
            return statusMap[status];
        },
    },
    data() {
        return {
            list: null,
            listLoading: false,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                equipTypeCode: "",
                partTypes: [],
                version: "",
            },

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设备类型",
                    prop: "equipTypeName",
                },
                {
                    label: "部件",
                    prop: "partTypeName",
                },
                {
                    label: "版本",
                    prop: "version",
                },

                {
                    label: "升级地址",
                    prop: "filePath",
                },
                { slot: "isUpdate", label: "是否自动升级" },
                {
                    label: "更新时间",
                    prop: "createTime",
                    formatter: (item) => {
                        return item.createTime
                            ? moment(item.createTime).format(
                                  "YYYY-MM-DD HH:mm:ss"
                              )
                            : "";
                    },
                },
                { slot: "connection", label: "关联设备", width: "160" },
                { slot: "action", label: "操作", width: "160" },
            ],
            tableData: [],
            visible: false, //弹框标识
            dialogForm: {
                equipTypeCode: "", //类型
                partType: "",
                version: "", //版本号
                md5: "", //MD5校验码
                filePath: "",
                fileName: "",
                remark: "",
                isAutoUpgrade: "",
                dowloadType: null,
                isEnable: null,
            },

            dialogTitle: "",

            equipTypeList: [],
            componentList: [],
            equipVisible: false,
            isFullscreen: true, //是否全屏
            versionId:"",//版本id
        };
    },
    computed: {
        ...mapGetters(["equipTypeCode"]),
    },

    created() {
        this.fetchData();
        this.getEquipType();
    },
    methods: {
        async getEquipType() {
            let data = await equipType("/datails", "post");
            this.equipTypeList = data.data;
        },
        async equipTypeChange(e) {
            this.componentList = [];
            this.searchForm.partTypes = [];
            let data = await partType("/list", "get", { equipTypeCode: e });
            this.componentList = data.data;
        },
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            this.tableData = [];
            this.total = 0;
            let param = { ...this.searchForm };

            softwareVersions(
                "/list",
                "post",
                {
                    ...removeNullUndefined(param),
                },
                1
            )
                .then((res) => {
                    if (res.code == 200) {
                        this.tableData = res.data;
                        this.total = +res.total;

                        this.searchForm.pageNum = +res.pageNum;
                    }
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        // 弹框取消
        cancelDialog() {
            this.visible = false;
            this.dialogForm = {
                equipTypeCode: "", //类型
                partType: "",
                version: "", //版本号
                md5: "", //MD5校验码
                filePath: "",
                fileName: "",
                remark: "",
                isAutoUpgrade: "",
                dowloadType: null,
                isEnable: null,
            };
        },
        updateData() {
            this.fetchData();
        },

        // 新增
        addDialog(row) {
            this.visible = true;
            this.dialogForm = {
                equipTypeCode: "", //类型
                partType: "",
                version: "", //版本号
                md5: "", //MD5校验码
                filePath: "",
                fileName: "",
                remark: "",
                isAutoUpgrade: "",
                dowloadType: null,
            };
            if (row.id) {
                this.dialogTitle = "编辑";
                this.$nextTick(() => {
                    this.dialogForm = { ...row };
                    this.dialogForm.isAutoUpgrade =
                        row.isAutoUpgrade == 1 ? true : false;
                });
            } else {
                this.dialogTitle = "新增";
            }
        },
        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert("submit!");
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },

        isCancelUpdate(e, row) {
            if (e == 1) {
                row.isAutoUpgrade = 0;
            } else {
                row.isAutoUpgrade = 1;
            }
            handleConfirm(
                `确定要${row.isAutoUpgrade === 1 ? "取消" : ""}自动升级吗？`,
                "warning",
                "提示"
            )
                .then((res) => {
                    this.doCancelUpdate(row);
                })
                .catch((err) => {});
        },
        // 取消自动升级
        doCancelUpdate(row) {
            softwareVersions(
                `/update/autoupgrade/${row.id}?isAutoUpgrade=${
                    row.isAutoUpgrade === 1 ? 0 : 1
                }`,
                "post",
                {},
                1
            ).then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },
        // 删除
        delDialog(row) {
            handleConfirm("删除后不可恢复，确定继续？", "warning", "提示")
                .then((res) => {
                    this.doDelete(row);
                })
                .catch((err) => {});
        },
        doDelete(row) {
            softwareVersions(`/delete/${row.id}`, "post").then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },
        // 搜索 重置
        resetSearch() {
            this.searchForm = {
                pageNum: this.searchForm.pageNum,
                pageSize: this.searchForm.pageSize,
                equipTypeCode: "",
                partTypes: [],
                version: "",
            };
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },
        switchChange(e) {
        },
        // 设备列表
        showEquipList(row) {
            this.equipVisible = true;
            this.versionId = row.id;
        },
        cancelEquipDialog() {
            this.equipVisible = false;
            this.isFullscreen = true;
        },
        onFullscreen(val) {
            this[val] = !this[val];
        },
        
    },
};
</script>
<style lang="scss" scoped>
.searchForm {
    padding-left: 8px;
    .el-form-item {
        margin-bottom: 8px;
    }
}
.detailDialog {
    ::v-deep .el-dialog__body {
        height: 72vh;
    }
}
.el-icon-full-screen {
    position: absolute;
    right: 45px;
    color: rgb(144, 147, 153);
    cursor: pointer;
    font-size: 22px;
    display: inline-block;
    margin-top: -44px;
    font-weight: bold;
}
</style>
